package com.neoCalf.neoCommon.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.neoCalf.neoCommon.enums.ResultCode;
import com.neoCalf.neoCommon.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


@Slf4j
public class JsonUtils {
    public static SerializerFeature[] FEATURES = new SerializerFeature[]{SerializerFeature.WriteMapNullValue};

    public static String convertObjToJson(Object object) {
        return JSON.toJSONString(object, FEATURES);
    }

    public static <T> T convertJsonToObj(String json, Class<T> tClass) throws BusinessException {
        try {
            return JSONObject.parseObject(json, tClass);
        } catch (Exception e) {
            log.error("发序列化异常: {}\n 错误:", json, e);
            throw new BusinessException(ResultCode.BusinessError);
        }
    }

    public static <T> List<T> convertJsonToArrayList(String json, Class<T> tClass) throws BusinessException {
        try {
            return JSONArray.parseArray(json, tClass);
        } catch (Exception e) {
            log.error("反序列化异常: {}\n 错误:", json, e);
            throw new BusinessException(ResultCode.BusinessError);
        }
    }
}
